package com._51doit.flinksql.test;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Rowtime;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @create: 2021-10-31 16:46
 * @author: 今晚打脑斧先森
 * @program: SQLTumblingEventWindow
 * @Description:
 **/
public class SQLTumblingEventWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.enableCheckpointing(12345);
        env.setParallelism(1);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        DataStreamSource<String> lines = env.socketTextStream("doit01", 8888);
        SingleOutputStreamOperator<Row> rowDataStream = lines.map(new MapFunction<String, Row>() {
            @Override
            public Row map(String value) throws Exception {
                String[] fields = value.split(",");
                Long time = Long.parseLong(fields[0]);
                String uid = fields[1];
//                String pid = fields[2];
                Double money = Double.parseDouble(fields[3]);
                return Row.of(time, uid, money);
            }
        }).returns(Types.ROW(Types.LONG, Types.STRING, Types.DOUBLE));
        SingleOutputStreamOperator<Row> watermarks = rowDataStream.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Row>(Time.seconds(0)) {
            @Override
            public long extractTimestamp(Row element) {
                return (long) element.getField(0);
            }
        });
        tableEnv.createTemporaryView("t_orders", watermarks, $("time"), $("uid"), $("money"), $("etime").rowtime());
        String sql = "SELECT uid, SUM(money) total_money, TUMBLE_START(etime, INTERVAL '10' SECOND) as win_start, " +
                "TUMBLE_END(etime, INTERVAL '10' SECOND) as win_end " +
                "FROM t_orders GROUP BY TUMBLE(etime, INTERVAL '10' SECOND), uid";

        Table table = tableEnv.sqlQuery(sql);
//        tableEnv.toRetractStream(table,Row.class).print();
        tableEnv.toAppendStream(table,Row.class).print();
        env.execute();
    }
}
